#include "mjpg.h"
#include "ui_mjpg.h"
#include "mjpegworker.h"

mjpg::mjpg(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::mjpg),
    networkManager(new QNetworkAccessManager(this)),
    reply(nullptr)
{
    ui->setupUi(this);
    ui->label_2->setStyleSheet("background-color: rgba(255, 255, 255, 0);color: black;font-family: '黑体'; font-size: 18px;");

    // 设置时间更新定时器
    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &mjpg::updateTime);
    timer->start(1000);
    updateTime();

    // 请求视频流
    connect(networkManager, &QNetworkAccessManager::finished, this, &mjpg::onNetworkReply);
    startStream();

}

mjpg::~mjpg()
{
    if (reply) {
        reply->abort();
        reply->deleteLater();
    }
    delete ui;
}

void mjpg::startStream()
{
    // 发起网络请求
        QNetworkRequest request(QUrl(*GlobalVal::mjpg_addr));
        reply = networkManager->get(request);

        // 创建并启动工作线程
        MJPEGWorker* worker = new MJPEGWorker(reply,ui->label);
        QThread* workerThread = new QThread(this);
        worker->moveToThread(workerThread);

        // 连接信号
        connect(workerThread, &QThread::started, worker, &MJPEGWorker::processFrame);
        connect(worker, &MJPEGWorker::updateImage, ui->label, &QLabel::setPixmap);
        connect(worker, &MJPEGWorker::finished, workerThread, &QThread::quit);
        connect(worker, &MJPEGWorker::finished, worker, &MJPEGWorker::deleteLater);
        connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater);

        workerThread->start();
}

void mjpg::onNetworkReply(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
            qDebug() << "Network error:" << reply->errorString();
        }
}


void mjpg::updateTime()
{
    // 更新时间标签
    ui->label_2->setText(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
}
